package com.gec.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gec.entity.ActiveUser;
import com.gec.entity.Employee;
import com.gec.service.EmployeeService;
import com.gec.service.impl.EmployeeServiceImpl;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class MyTaskListener implements TaskListener{

    @Override
    public void notify(DelegateTask delegateTask) {

        //获取spring容器对象
        ApplicationContext context = SpringUtil.getApplicationContext();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //获取当前用户
        ActiveUser activeUser = (ActiveUser) request.getSession().getAttribute("activeUser");
        //通过当前用户获取上级
        EmployeeService employeeService = (EmployeeServiceImpl) context.getBean("employeeServiceImpl");

        QueryWrapper<Employee> ew = new QueryWrapper<>();
        ew.eq("id", activeUser.getManagerId());
        List<Employee> managers = employeeService.list(ew);

        //获取taskService
        TaskService taskService = (TaskService) context.getBean("taskServiceBean");
        for (Employee manager : managers) {
            System.out.println(manager);

            //设置流程候选人
            taskService.addCandidateUser(delegateTask.getId(), manager.getId() + "_" + manager.getName());
        }
    }
}
